<template>
  <div>
    <header class="mui-bar mui-bar-nav">
        <a class="iconfont icon-fanhui header_fanhui" @tap="back()" style="margin-top:0px;padding-bottom:0px;padding-top:0px"></a>  
        <h1 class="mui-title" >扫一扫</h1> 
        <span  class="mui-icon mui-icon-spinner-cycle mui-spin mui-pull-right" id="turnTheLight" style="margin-top:6px;"></span>   
    </header>
    <div id="bcid">
		</div>
		<div class="mui-bar mui-bar-footer" style="padding: 0px;">  
        <div class="fbt" @click="scanPicture()">从相册选择二维码</div>  
        <div class="fbt" @tap="back()">取　 消</div>  
    </div>  
  </div>
</template>
<script>
import mui from 'static/js/mui'
import {addSalerToCustomer} from '@/api/user'
import storage from "@/utils/localstorage" 
export default {
  data() {
    return {
      userInfo: ''
    }
  },
  created() {
    this.userInfo = storage.getLocalstorage('user')
  },
  mounted() {
    mui.init({
        keyEventBind: {
            backbutton: true  //关闭back按键监听
        }
    })
    mui.back = function () {
        history.go(-1)
    }
    if(window.plus){
      this.plusReady()
    }
    else{
      // 无法调用跳提示回主页
      /* this.$router.push({
        path: "/home"
      }) */
    }
  },
  //注意销毁掉监听，不然报错
  destroyed () { 
    //抓报错
    window.scan.close()
    window.sacn = null
  },
  methods: {
    back() {
      //关闭控件
      try{
        window.scan.close();
      }catch(err){
          //console.log('逻辑错误')
      }
      this.$router.push({
        path: "/home"
      })
    },
    plusReady (){
      try{  
        var filter;  
        //自定义的扫描控件样式  
        var styles = {frameColor: "#29E52C",scanbarColor: "#29E52C",background: ""}  
        //扫描控件构造  
        window.scan = new plus.barcode.Barcode('bcid',filter,styles);  
        scan.onmarked = this.onmarked;   
        scan.onerror = this.onerror;  
        scan.start();  
        //打开关闭闪光灯处理  
        var flag = false;  
        document.getElementById("turnTheLight").addEventListener('tap',function(){  
            if(flag == false){  
              scan.setFlash(true);  
              flag = true;  
            }else{  
              scan.setFlash(false);  
              flag = false;  
            }  
        });  
      }catch(e){  
        alert("出现错误啦:\n"+e);  
      }  

    },
    // 错误信息弹窗
    onerror(e) {
       alert(e);
    },
    // 解析二维码后回调此方法
    onmarked(type, result, file){
      //相册读取会有双引号，需要去除
      result = result.replace(/\"/g, "");
      switch(type){
        case plus.barcode.QR:
        type = 'QR';
        break;
        case plus.barcode.EAN13:
        type = 'EAN13';
        break;
        case plus.barcode.EAN8:
        type = 'EAN8';
        break;
        default:
        type = '其它'+type;
        break;
      }
      // 采集导购码
      let that = this
      if((result.substring(0,2) === 'DG')){
        let Base64 = require('js-base64').Base64
        let salerId = Base64.encode(result.substring(2,result.length))
        let QRcodeData = {'QRcode': salerId, 'mobile': this.userInfo.mobile} 
        addSalerToCustomer(QRcodeData).then(res=>{
          if(res.msg == 'success'){
            //console.log(res.data.bidCar_orderPrice)
            storage.setLocalstorage('user',  res.data)
            window.scan.close();
            that.$router.push('/home')
            mui.alert('您已绑定导购员:'+res.data.salerName, '', ['确定'],function() {},'div');
          }
          else if(res.data == ""){
            window.scan.close();
            that.$router.push('/home')
            mui.alert(res.msg, '', ['确定'],function(
            ) {},'div');
          }
        })
      }else{
        mui.alert('扫描的是无效导购二维码','温馨提醒', ['确定'],function() {},'div')
      }  
    },
    scanPicture() {
      var that = this
      plus.gallery.pick(function(path){
        plus.barcode.scan(path,that.onmarked,function(error){
        plus.nativeUI.alert('无法识别此图片');
      });
      }, function(err){
          //console.log('Failed: '+err.message);
      });
    }
  }
}
</script>
<style scoped>
 .mui-icon{
   padding-top: 5px!important;
 }
 #bcid{  
    width: 100%;
    position: absolute;
    top: 44px;
    background-color: #000000;
    bottom: 44px;
  }  
  #turnTheLight{
    height:44px;
    line-height: 44px;
    position: relative;
    top:-12px;
  }
  .fbt:active {
  	-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.5);
    box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.5);
  }
  .mui-icon{
    padding-top: 10px; 
    padding-bottom: 10px; 
  }
  header{
    background-image:none!important;
    background:white;
  }
  .mui-title{
    color: #333333;
  }
  .header_fanhui{
    line-height: 43px;
    font-size: 0.9rem;
    width: 43px;
  }
</style>
